import traceback

from django.utils.deprecation import MiddlewareMixin

from base.tasks import email_error
from map_backend.logger import dayLogger, errorLogger


class MapMiddleware(MiddlewareMixin):
    def process_request(self, request):
        path = request.build_absolute_uri()  # 用户访问的接口路径
        method = request.method  # 请求方法（如 GET, POST 等）
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip_address = request.META.get('HTTP_X_FORWARDED_FOR')
        else:
            ip_address = request.META.get('REMOTE_ADDR')
        dayLogger.info(f"Request: path={path}, method={method}, ip_address={ip_address}")
        return None

    def process_exception(self, request, exception, email_verify_code=None):
        errorLogger.error(f'错误：{exception}')
        full_traceback = traceback.format_exc()
        email_error.delay(full_traceback)
        return None
